package com.gzg.userservice.interceptor;
import com.gzg.userservice.Exception.MyException;
import com.gzg.userservice.utils.UserContext;
import com.gzg.userservice.utils.jwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RequiredArgsConstructor
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private final jwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        try {
            // 1.获取请求头中的 token
            String token = request.getHeader("authorization");
            // 2.校验token
            Long userId = jwtUtils.verify(token).getClaim("userId").asLong();
            // 3.存入上下文
            UserContext.setUser(userId);
        } catch (Exception e) {
            throw new MyException("用户未登录");
        }
        return true;
    }
}
